import java.util.LinkedList;
import java.util.Queue;

/**
 * 200. 岛屿数量
 * https://leetcode.cn/problems/number-of-islands/description/
 */
class Solution2 {
    int[] dx = {-1, 1, 0, 0};
    int[] dy = {0, 0, 1, -1};
    boolean[][] vis;
    int m, n;
    Queue<int[]> q;

    public int numIslands(char[][] grid) {
        int ret = 0;
        m = grid.length;//行
        n = grid[0].length;//列
        vis = new boolean[m][n];
        for(int i = 0; i < m; i++) {
            for(int j = 0; j < n; j++) {
                if(grid[i][j] == '1' && !vis[i][j]) {
                    ret++;
                    bfs(grid, i, j);
                }
            }
        }
        return ret;
    }

    public void bfs(char[][] grid, int i, int j) {
        q = new LinkedList<>();
        q.offer(new int[]{i, j});
        while(!q.isEmpty()) {
            int[] tmp = q.poll();
            int a = tmp[0], b = tmp[1];
            for(int k = 0; k < 4; k++) {
                int x = a + dx[k], y = b + dy[k];
                if(x >= 0 && x < m && y >= 0 && y < n && grid[x][y] == '1' && !vis[x][y]) {
                    q.offer(new int[]{x, y});
                    vis[x][y] = true;
                }
            }
        }
    }
}